package com.liuyu.common.framework.template.htmltopdf.utils;

import com.google.common.collect.Maps;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.StringWriter;
import java.util.Map;

/**
 *
 * @author liuyu
 * @date 2021/8/23 15:45
 */
public class FreeMarkerUtil {
    private static Map<String, Configuration> configurationCache = Maps.newConcurrentMap();
    private static Map<String, FileTemplateLoader> fileTemplateLoaderCache = Maps.newConcurrentMap();

    /**
     * 生成配置
     * @param templateFilePath
     * @return
     * @throws Exception
     */
    public static Configuration getConfiguration(String templateFilePath) throws Exception {
        if (null != configurationCache.get(templateFilePath)) {
            return configurationCache.get(templateFilePath);
        }

        Configuration config = new Configuration(Configuration.VERSION_2_3_22);
        config.setDefaultEncoding("UTF-8");
        config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        config.setLogTemplateExceptions(false);
        FileTemplateLoader fileTemplateLoader = null;
        if (null != fileTemplateLoaderCache.get(templateFilePath)) {
            fileTemplateLoader = fileTemplateLoaderCache.get(templateFilePath);
        }

        fileTemplateLoader = new FileTemplateLoader(new File(templateFilePath));
        fileTemplateLoaderCache.put(templateFilePath, fileTemplateLoader);

        config.setTemplateLoader(fileTemplateLoader);
        configurationCache.put(templateFilePath, config);
        return config;
    }

    /**
     * 按模板生成
     * @param templatePath
     * @param data
     * @return
     */
    public static String getContent(String templatePath, Object data) throws Exception {
        File templateFile = new File(templatePath);
        String templateFileName = templateFile.getName();
        String templateFilePath = templateFile.getParent();

        Template template = getConfiguration(templateFilePath).getTemplate(templateFileName);
        StringWriter writer = new StringWriter();
        template.process(data, writer);
        writer.flush();
        return writer.toString();
    }
}
